<!--
 * Copyright © 2023
 * @Author: zhangxiang
 * @Date: 2023-07-03 14:58:02
 * @LastEditors: zhangxiang
 * @LastEditTime: 2023-09-04 11:26:59
 * @Description:
 *
-->

<template>
  <el-form
    ref="form"
    class="create-basic"
    :rules="rules"
    :model="form"
    label-width="80px"
    size="medium"
  >
    <el-form-item class="item" label="云服务商" prop="cloudProvider">
      <el-select
        v-model="form.cloudProvider"
        placeholder="请选择云服务商"
        style="width: 100%"
        :disabled="true"
      >
        <el-option
          v-for="item in cloudProviderOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item class="item right" label="云账户" prop="cloudAccountName">
      <el-select
        v-model="form.cloudAccountName"
        placeholder="请选择云账户"
        style="width: 100%"
        no-data-text="请选择云服务商"
      >
        <el-option
          v-for="item in cloudAccountNameOptions"
          :key="item.cloudAccountName"
          :label="item.cloudAccountName"
          :value="item.cloudAccountName"
        />
      </el-select>
    </el-form-item>
    <el-form-item class="item" label="主机名称" prop="vmName">
      <el-row type="flex" align="middle">
        <el-input v-model="form.vmName" placeholder="请输入主机名称" />
        <el-popover placement="right" width="250" trigger="hover">
          <p v-html="nameRule"></p>
          <i
            slot="reference"
            class="el-icon-info icon"
            style="font-size: 18px; margin-left: 10px"
          ></i>
        </el-popover>
      </el-row>
    </el-form-item>
    <el-form-item class="item right" label="计费模式" prop="chargeParam">
      <el-row type="flex" align="middle" style="height: 36px">
        <el-radio-group v-model="form.chargeType" @input="chargeTypeChange">
          <el-radio
            v-for="item in chargeTypeOptions"
            :key="item.value"
            :label="item.value"
          >{{ item.label }}</el-radio>
        </el-radio-group>
        <el-select
          v-if="form.chargeType === '包年/包月'"
          v-model="chargePeriod"
          placeholder="请选择时长"
          style="flex: 1; margin-left: 10px"
          size="small"
        >
          <el-option
            v-for="item in chargePeriodOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-row>
    </el-form-item>
    <el-form-item class="item" label="区域" prop="cpRegionId">
      <el-select
        v-model="form.cpRegionId"
        placeholder="请选择区域"
        no-data-text="请选择合适的云服务商"
        style="width: 100%"
      >
        <el-option
          v-for="item in regionOptions"
          :key="item.cpId"
          :label="item.desc"
          :value="item.cpId"
        />
      </el-select>
    </el-form-item>
    <el-form-item class="item right" label="可用区" prop="zone">
      <el-select
        v-model="form.zone"
        placeholder="请选择可用区"
        no-data-text="请先选择区域"
        style="width: 100%"
      >
        <el-option
          v-for="item in zoneOptions"
          :key="item.key"
          :label="item.text"
          :value="item.key"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="规格" prop="flavorId">
      <el-row type="flex" justify="center">
        <el-select
          v-model="flavorSelector.arch"
          placeholder="请选择规格类型"
          style="flex: 1.2; margin-right: 10px"
          clearable
        >
          <el-option
            v-for="item in archOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="flavorSelector.cpuCount"
          placeholder="请选择vCPUs"
          style="flex: 1; margin-right: 10px"
          clearable
        >
          <el-option
            v-for="item in cpuCountOptions"
            :key="item.value"
            :label="item.label + 'vCPUs'"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="flavorSelector.memSize"
          placeholder="请选择内存"
          style="flex: 1; margin-right: 10px"
          clearable
        >
          <el-option
            v-for="item in memSizeOptions"
            :key="item.value"
            :label="item.label + 'GiB'"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="form.flavorId"
          placeholder="请选择规格"
          :loading="loadingFlavorIdOptions"
          no-data-text="请选择合适的云账户、区域及规格过滤条件"
          style="flex: 3"
        >
          <el-option
            v-for="item in flavorIdOptions"
            :key="item.id"
            :label="
              item.name +
                ' (' +
                item.cpuCount +
                'C | ' +
                item.memSize +
                'G' +
                (item.gpu ? ' | ' + item.gpu : '') +
                (item.gpuMemSize ? ' | ' + item.gpuMemSize : '') +
                ')'
            "
            :value="item.id"
          />
        </el-select>
      </el-row>
    </el-form-item>
    <el-form-item class="item" label="镜像" prop="imageOs">
      <el-select
        v-model="form.imageOs"
        placeholder="请选择操作系统"
        style="width: 100%"
      >
        <el-option
          v-for="item in imageOsOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item class="item right" label-width="0px" label="" prop="imageId">
      <el-select
        v-model="form.imageId"
        placeholder="请选择相应镜像"
        :loading="loadingImageIdOptions"
        no-data-text="请选择合适的区域及规格"
        style="width: 100%"
        filterable
        @change="imageIdChange"
      >
        <el-option
          v-for="item in imageIdOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item class="item" label="系统盘" prop="sysDiskType">
      <el-select
        v-model="form.sysDiskType"
        placeholder="请选择系统盘"
        style="width: 100%"
        no-data-text="请先选择区域及可用区"
      >
        <el-option
          v-for="item in sysDiskTypeOptions"
          :key="item.zhName"
          :label="item.zhName"
          :value="item.zhName"
        />
      </el-select>
    </el-form-item>
    <el-form-item class="item right sysDiskSize" label="" prop="sysDiskSize">
      <el-input-number
        v-model="form.sysDiskSize"
        :min="sysDiskSizeMin"
        :max="500"
        :step="10"
        :precision="0"
        label="系统盘大小"
      />
      <span style="margin-left: 10px">GB</span>
    </el-form-item>
    <el-form-item label="描述" prop="desc">
      <el-input
        v-model="form.desc"
        placeholder="请输入描述"
        type="textarea"
        :rows="3"
      />
    </el-form-item>
  </el-form>
</template>

<script>
import resSelectorMixin from '@/views/mixin/resSelector.js'
import {
  getRegionList,
  queryImage,
  queryInstanceType,
  getBlockVolumeType
} from '@/api/cn-resource'
import {
  CLOUD_HUAWEI_IMAGE_OS,
  CPU_ARCH_HUAWEI,
  VCPUS_HUAWEI,
  MEM_SIZE_HUAWEI
} from '@/utils/constant'
import debounce from 'lodash/debounce'

const MIN_DISK_SIZE = 20
const NAME_RULE =
  '长度范围为1-64位，只能由中文字符、英文字母、数字及“_”、“-”、“.”组成'

export default {
  name: 'CreateBasicHuawei',
  components: {},
  mixins: [resSelectorMixin],
  props: {
    cloudSelect: {
      type: String,
      default: ''
    }
  },
  data() {
    /**
     * @description: 检验计费相关参数
     * @param {*} rule
     * @param {*} value
     * @param {*} callback
     * @return {*}
     */
    var validateChargeParam = (rule, value, callback) => {
      if (this.form.chargeType === '') {
        callback(new Error('请选择计费模式'))
      } else if (
        this.form.chargeType === '包年/包月' &&
        this.chargePeriod === ''
      ) {
        callback(new Error('请选择包年/包月时长'))
      } else {
        callback()
      }
    }
    return {
      nameRule: NAME_RULE,
      chargeTypeOptions: [
        {
          label: '按需计费',
          value: '按需计费'
        },
        {
          label: '包年/包月',
          value: '包年/包月'
        }
      ],
      chargePeriod: '',
      chargePeriodOptions: [
        {
          label: '1个月',
          value: '1个月',
          unit: 'month',
          period: '1'
        },
        {
          label: '2个月',
          value: '2个月',
          unit: 'month',
          period: '2'
        },
        {
          label: '3个月',
          value: '3个月',
          unit: 'month',
          period: '3'
        },
        {
          label: '4个月',
          value: '4个月',
          unit: 'month',
          period: '4'
        },
        {
          label: '5个月',
          value: '5个月',
          unit: 'month',
          period: '5'
        },
        {
          label: '6个月',
          value: '6个月',
          unit: 'month',
          period: '6'
        },
        {
          label: '7个月',
          value: '7个月',
          unit: 'month',
          period: '7'
        },
        {
          label: '8个月',
          value: '8个月',
          unit: 'month',
          period: '8'
        },
        {
          label: '9个月',
          value: '9个月',
          unit: 'month',
          period: '9'
        },
        {
          label: '1年',
          value: '1年',
          unit: 'year',
          period: '1'
        },
        {
          label: '2年',
          value: '2年',
          unit: 'year',
          period: '2'
        },
        {
          label: '3年',
          value: '3年',
          unit: 'year',
          period: '3'
        },
        {
          label: '4年',
          value: '4年',
          unit: 'year',
          period: '4'
        },
        {
          label: '5年',
          value: '5年',
          unit: 'year',
          period: '5'
        }
      ],
      regionOptions: [],
      zoneOptions: [],
      imageOsOptions: CLOUD_HUAWEI_IMAGE_OS,
      loadingImageIdOptions: false,
      imageIdOptions: [],
      flavorIdOptions: [],
      loadingFlavorIdOptions: false,
      sysDiskTypeOptions: [],
      sysDiskSizeMin: MIN_DISK_SIZE,
      archOptions: CPU_ARCH_HUAWEI,
      cpuCountOptions: VCPUS_HUAWEI,
      memSizeOptions: MEM_SIZE_HUAWEI,
      flavorSelector: {
        arch: '',
        cpuCount: '',
        memSize: ''
      },
      form: {
        cloudProvider: '', // 云服务商
        cloudAccountName: '', // 云账户
        vmName: '', // 主机名称
        chargeType: '', // 计费模式
        period: '',
        periodUnit: '',
        cpRegionId: '', // 区域
        zone: '', // 可用区
        imageOs: CLOUD_HUAWEI_IMAGE_OS[0].value, // 镜像系统
        imageId: '', // 镜像
        flavorId: '', // 规格
        sysDiskType: '', // 系统盘
        sysDiskSize: '40', // 系统盘大小
        desc: '' // 描述
      },
      rules: {
        cloudProvider: [
          { required: true, message: '请选择云服务商', trigger: 'change' }
        ],
        cloudAccountName: [
          { required: true, message: '请选择云账户', trigger: 'change' }
        ],
        vmName: [
          { required: true, message: '请输入主机名称', trigger: 'blur' },
          {
            pattern: /^[\u4e00-\u9fa5\-\._a-zA-Z0-9]{1,64}$/,
            message: NAME_RULE
          }
        ],
        chargeParam: [
          {
            required: true,
            validator: validateChargeParam
          }
        ],
        cpRegionId: [
          { required: true, message: '请选择区域', trigger: 'change' }
        ],
        zone: [{ required: true, message: '请选择可用区', trigger: 'change' }],
        imageOs: [
          { required: true, message: '请选择操作系统', trigger: 'change' }
        ],
        imageId: [
          { required: true, message: '请选择相应镜像', trigger: 'change' }
        ],
        flavorId: [
          { required: true, message: '请选择规格', trigger: 'change' }
        ],
        sysDiskType: [
          { required: true, message: '请选择系统盘', trigger: 'change' }
        ],
        sysDiskSize: [
          { required: true, message: '请输入系统盘大小', trigger: 'blur' }
        ]
      },
      flavorQueryDebounce: null,
      sysDiskTypeQueryDebounce: null,
      imageIdQueryDebounce: null
    }
  },
  computed: {
    /**
     * @description: 规格相关参数
     * @return {*}
     */
    flavorParam() {
      return {
        cloudAccountName: this.form.cloudAccountName,
        cpRegionId: this.form.cpRegionId,
        zone: this.form.zone,
        chargeType: this.form.chargeType,
        arch: this.flavorSelector.arch,
        cpuCount: this.flavorSelector.cpuCount,
        memSize: this.flavorSelector.memSize
      }
    },
    /**
     * @description: 系统盘相关参数
     * @return {*}
     */
    sysDiskTypeParam() {
      return {
        cloudAccountName: this.form.cloudAccountName,
        cpRegionId: this.form.cpRegionId,
        zone: this.form.zone
      }
    },
    /**
     * @description: 镜像相关参数
     * @return {*}
     */
    imageIdParam() {
      return {
        cloudAccountName: this.form.cloudAccountName,
        imageOs: this.form.imageOs,
        cpRegionId: this.form.cpRegionId,
        cpFlavorId: this.form.flavorId
      }
    }
  },
  watch: {
    /**
     * @description: 监听镜像相关参数
     * @return {*}
     */
    imageIdParam: {
      handler(newVal) {
        this.form.imageId = ''
        this.imageIdOptions = []
        if (!this.imageIdQueryDebounce) {
          // 创建防抖函数
          this.imageIdQueryDebounce = debounce(() => {
            if (
              this.form.cloudAccountName &&
              this.form.cpRegionId &&
              this.form.flavorId
            ) {
              this.getImageList()
            }
          }, 300)
        }
        this.imageIdQueryDebounce()
      },
      immediate: true,
      deep: true
    },
    /**
     * @description: 监听系统盘相关参数
     * @return {*}
     */
    sysDiskTypeParam: {
      handler(newVal) {
        this.form.sysDiskType = ''
        this.sysDiskTypeOptions = []
        if (!this.sysDiskTypeQueryDebounce) {
          // 创建防抖函数
          this.sysDiskTypeQueryDebounce = debounce(() => {
            if (
              this.form.cloudAccountName &&
              this.form.cpRegionId &&
              this.form.zone
            ) {
              this.getDiskType()
            }
          }, 300)
        }
        this.sysDiskTypeQueryDebounce()
      },
      immediate: true,
      deep: true
    },
    /**
     * @description: 监听规格相关参数
     * @return {*}
     */
    flavorParam: {
      handler(newVal) {
        this.form.flavorId = ''
        if (!this.flavorQueryDebounce) {
          // 创建防抖函数
          this.flavorQueryDebounce = debounce(() => {
            if (
              this.form.cloudAccountName &&
              this.form.cpRegionId &&
              this.form.chargeType
            ) {
              this.getFlavorList()
            }
          }, 300)
        }
        this.flavorQueryDebounce()
      },
      immediate: true,
      deep: true
    },
    /**
     * @description: 监听 包年包月时长 变化
     * @return {*}
     */
    chargePeriod: {
      handler(newVal) {
        if (newVal) {
          const chargeFind = this.chargePeriodOptions.find((item) => {
            return item.value === newVal
          })
          if (chargeFind) {
            this.form.period = chargeFind.period
            this.form.periodUnit = chargeFind.unit
          } else {
            this.form.period = ''
            this.form.periodUnit = ''
          }
        } else {
          this.form.period = ''
          this.form.periodUnit = ''
        }
      },
      immediate: true,
      deep: true
    },
    /**
     * @description: 区域监听
     * @return {*}
     */
    'form.cpRegionId': {
      handler(newVal) {
        if (newVal) {
          // 公有云
          const regionSelect = this.regionOptions.find((item) => {
            return newVal === item.cpId
          })
          // 设置可用区
          if (regionSelect && Array.isArray(regionSelect.zones)) {
            this.zoneOptions = regionSelect.zones.filter((item) => {
              return item.val
            })
          } else {
            this.zoneOptions = []
          }
          this.form.zone = ''
        }
      },
      immediate: true
    },
    /**
     * @description: 云商监听
     * @return {*}
     */
    'form.cloudProvider': {
      handler(newVal) {
        if (newVal) {
          this.form.cloudAccountName = ''
          // 获取区域
          this.form.cpRegionId = ''
          this.form.zone = ''
          this.getRegionList()
        }
      },
      immediate: true
    },
    /**
     * @description: 云商选择监听
     * @return {*}
     */
    cloudSelect: {
      handler(newVal) {
        if (newVal) {
          this.form.cloudProvider = this.cloudSelect
        }
      },
      immediate: true
    }
  },
  mounted() {},
  methods: {
    /**
     * @description: 计费模式 改变
     * @param {*} val
     * @return {*}
     */
    chargeTypeChange(val) {
      if (val === '按需计费') {
        this.chargePeriod = ''
      }
    },
    /**
     * @description: 获取系统盘类型
     * @return {*}
     */
    getDiskType() {
      getBlockVolumeType({
        cloudProvider: this.form.cloudProvider,
        cloudAccountName: this.form.cloudAccountName,
        cpRegionId: this.form.cpRegionId,
        cpZoneId: this.form.zone
      }).then((res) => {
        this.sysDiskTypeOptions = Array.isArray(res.data) ? res.data : []
      })
    },
    /**
     * @description: 获取规格
     * @return {*}
     */
    getFlavorList() {
      this.loadingFlavorIdOptions = true
      queryInstanceType({
        cloudProvider: this.form.cloudProvider,
        cloudAccountName: this.form.cloudAccountName,
        chargeType: this.form.chargeType,
        region: this.form.cpRegionId,
        zone: this.form.zone,
        arch: this.flavorSelector.arch,
        cpuCount: this.flavorSelector.cpuCount,
        memSize: this.flavorSelector.memSize
      })
        .then((res) => {
          this.flavorIdOptions = Array.isArray(res.data)
            ? res.data.slice(0, Math.min(res.data.length, 200))
            : []
        })
        .finally(() => {
          this.loadingFlavorIdOptions = false
        })
    },
    /**
     * @description: 镜像选择
     * @param {*} val
     * @return {*}
     */
    imageIdChange(val) {
      const imageSelect = this.imageIdOptions.find((item) => {
        return item.id === val
      })
      this.sysDiskSizeMin =
        imageSelect && imageSelect.minDiskSize
          ? imageSelect.minDiskSize
          : MIN_DISK_SIZE
      this.form.sysDiskSize = Math.max(
        this.sysDiskSizeMin,
        this.form.sysDiskSize
      )
    },
    /**
     * @description: 获取镜像
     * @return {*}
     */
    getImageList() {
      this.loadingImageIdOptions = true
      let cpFlavorId = ''
      const flavorSelect = this.flavorIdOptions.find((item) => {
        return this.form.flavorId === item.id
      })
      if (flavorSelect) {
        cpFlavorId = flavorSelect.cpId
      }
      queryImage({
        cloudProvider: this.form.cloudProvider,
        cloudAccountName: this.form.cloudAccountName,
        osPlatform: this.form.imageOs,
        region: this.form.cpRegionId,
        cpFlavorId: cpFlavorId
      })
        .then((res) => {
          this.imageIdOptions = Array.isArray(res.data) ? res.data : []
        })
        .finally(() => {
          this.loadingImageIdOptions = false
        })
    },
    /**
     * @description: 获取区域
     * @return {*}
     */
    getRegionList() {
      getRegionList({
        keyword: this.form.cloudProvider,
        pageNum: 1,
        pageSize: 100
      }).then((res) => {
        if (res.data) {
          this.regionOptions = Array.isArray(res.data.data)
            ? res.data.data
            : []
        } else {
          this.regionOptions = []
        }
      })
    },
    /**
     * @description: 校验
     * @return {*}
     */
    validateForm(callback) {
      this.$refs.form.validate((valid, obj) => {
        if (valid) {
          const extraForm = this.getExtraForm()
          callback({
            isCloudPublic: this.isCloudProviderPublic,
            ...extraForm,
            ...this.form
          })
        }
      })
    },
    /**
     * @description: 获取表单参数额外展示的数据
     * @return {*}
     */
    getExtraForm() {
      // 获取flavorDetail
      const flavorSelect = this.flavorIdOptions.find((item) => {
        return this.form.flavorId === item.id
      })
      const flavorDetail = flavorSelect
        ? flavorSelect.name +
          ' (' +
          flavorSelect.cpuCount +
          'C | ' +
          flavorSelect.memSize +
          'G' +
          (flavorSelect.gpu ? ' | ' + flavorSelect.gpu : '') +
          (flavorSelect.gpuMemSize ? ' | ' + flavorSelect.gpuMemSize : '') +
          ')'
        : ''
      // 获取imageDetail
      const imageSelect = this.imageIdOptions.find((item) => {
        return this.form.imageId === item.id
      })
      const imageDetail = imageSelect ? imageSelect.os : ''
      // 获取zoneText
      const zoneSelect = this.zoneOptions.find((item) => {
        return this.form.zone === item.key
      })
      const zoneText = zoneSelect ? zoneSelect.text : ''
      // 获取regionDesc
      const regionSelect = this.regionOptions.find((item) => {
        return this.form.cpRegionId === item.cpId
      })
      const regionDesc = regionSelect ? regionSelect.desc : ''
      return {
        flavorDetail,
        imageDetail,
        zoneText,
        regionDesc,
        chargePeriod: this.chargePeriod
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import "@/assets/css/common.less";
.create-basic {
  .item {
    display: inline-block;
    width: calc(50% - 12.5px);
    &.right {
      margin-left: 25px;
    }
    &.sysDiskSize {
      /deep/ .el-form-item__content {
        margin-left: 5px !important;
      }
    }
  }
}
</style>
